﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace ActiveStory.UI
{
    /// <summary>
    /// Interaction logic for ExportWindow.xaml
    /// </summary>
    public partial class ExportWindow : Window
    {
        private bool _cassiniInstalled = false;

        public enum ExportMode { WizardOfOz, CurrentPage, AllPages, Error };
        
        public ExportMode SelectedExportMode
        {
            get
            {
                switch (ExportTabControl.SelectedIndex)
                {
                    case 0:
                        return ExportMode.WizardOfOz;
                    case 1:
                        return ExportMode.CurrentPage;
                    case 2:
                        return ExportMode.AllPages;
                    default:
                        return ExportMode.Error;
                }
            }
        }

        public ActiveStoryApplication.ServerHostType SelectedServerHostType
        {
            get
            {
                if (ExportTabControl.SelectedIndex != 0)
                    return ActiveStoryApplication.ServerHostType.Error;
                int index = WoZExportTypeComboBox.SelectedIndex;
                if (!_cassiniInstalled)
                    index += 1;
                switch (index)
                {
                    case 0:
                        return ActiveStoryApplication.ServerHostType.BuiltIn;
                    case 1:
                        return ActiveStoryApplication.ServerHostType.External;
                    default:
                        return ActiveStoryApplication.ServerHostType.Error;
                }
            }
        }

        public int SelectedStartupPageNumber
        {
            get
            {
                return (int)StartupPageNumberComboBox.SelectedValue - 1;    //page numbers are shown base 1, revert to base 0 for processing
            }
        }

        public String TaskInstructions
        {
            get
            {
                return TaskInstructionsTextBox.Text;
            }
        }

        public ActiveStoryApplication.ImageFormat SelectedImageFormat
        {
            get
            {
                if (ExportTabControl.SelectedIndex == 1)        //Export Current Page
                {
                    switch (PageImageFormatComboBox.SelectedIndex)
                    {
                        case 0:
                            return ActiveStoryApplication.ImageFormat.PNG;
                        case 1:
                            return ActiveStoryApplication.ImageFormat.GIF;
                        case 2:
                            return ActiveStoryApplication.ImageFormat.JPG;
                        case 3:
                            return ActiveStoryApplication.ImageFormat.BMP;
                        case 4:
                            return ActiveStoryApplication.ImageFormat.TIFF;
                        default:
                            return ActiveStoryApplication.ImageFormat.Error;
                    }
                }
                else if (ExportTabControl.SelectedIndex == 2)   //Export All Pages
                {
                    switch (ExportAllImageFormatComboBox.SelectedIndex)
                    {
                        case 0:
                            return ActiveStoryApplication.ImageFormat.PNG;
                        case 1:
                            return ActiveStoryApplication.ImageFormat.GIF;
                        case 2:
                            return ActiveStoryApplication.ImageFormat.JPG;
                        case 3:
                            return ActiveStoryApplication.ImageFormat.BMP;
                        case 4:
                            return ActiveStoryApplication.ImageFormat.TIFF;
                        default:
                            return ActiveStoryApplication.ImageFormat.Error;
                    }
                }
                else                                        //Export to web server, no image format
                    return ActiveStoryApplication.ImageFormat.Error;
            }
        }

        public String TargetDirectory
        {
            get
            {
                if (ExportTabControl.SelectedIndex == 1)    //Export Current Page
                {
                    return PageExportDirectoryTextBox.Text;
                }
                else if (ExportTabControl.SelectedIndex == 2)       //Export All Pages
                {
                    return ExportAllDirectoryTextBox.Text;
                }
                else                                                //Export to web server
                    return WoZExportDirectoryTextBox.Text;
            }
        }

        public ExportWindow()
        {
            InitializeComponent();
            _cassiniInstalled = IsCassiniInstalled();
        }

        private void BrowseForDirectoryCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if ((Button)e.Source == WoZBrowseButton)
            {
                System.Windows.Forms.FolderBrowserDialog fbd = new System.Windows.Forms.FolderBrowserDialog();
                fbd.ShowNewFolderButton = true;
                fbd.Description = "Choose the server's www folder or a temporary folder:";
                System.Windows.Forms.DialogResult dr = fbd.ShowDialog();
                if (!dr.Equals(System.Windows.Forms.DialogResult.OK))
                {
                    return;
                }
                WoZExportDirectoryTextBox.Text = fbd.SelectedPath;
            }
            else if ((Button)e.Source == PageExportBrowseButton)
            {
                Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
                switch (PageImageFormatComboBox.SelectedIndex)
                {
                    case 0:
                        sfd.Filter = "Portable Network Graphics (.png)|*.png";
                        break;
                    case 1:
                        sfd.Filter = "CompuServe Graphics Interchange Format (.gif)|*.gif";
                        break;
                    case 2:
                        sfd.Filter = "JPEG Image (.jpg)|*.jpg";
                        break;
                    case 3:
                        sfd.Filter = "Bitmap Image (.bmp)|*.bmp";
                        break;
                    case 4:
                        sfd.Filter = "Tagged Image File Format (.tiff)|*.tiff";
                        break;
                    default:
                        MessageBox.Show(this, "Select an image format for the exported image.", "Error: Invalid Image Format", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                }
                sfd.OverwritePrompt = true;
                sfd.AddExtension = true;
                if (!(bool)sfd.ShowDialog(this))
                    return;
                PageExportDirectoryTextBox.Text = sfd.FileName;
            }
            else if ((Button)e.Source == ExportAllBrowseButton)
            {
                System.Windows.Forms.FolderBrowserDialog fbd = new System.Windows.Forms.FolderBrowserDialog();
                fbd.ShowNewFolderButton = true;
                fbd.Description = "Choose the folder to export the images to:";
                System.Windows.Forms.DialogResult dr = fbd.ShowDialog();
                if (!dr.Equals(System.Windows.Forms.DialogResult.OK))
                {
                    return;
                }
                ExportAllDirectoryTextBox.Text = fbd.SelectedPath;
            }
        }

        private void BrowseForDirectoryCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if ((Button)e.Source == WoZBrowseButton)
            {
                if (_cassiniInstalled)
                {
                    if (WoZExportTypeComboBox.SelectedIndex == 0)      //Built-in server, so disable
                    {
                        e.CanExecute = false;
                        return;
                    }
                }
            }
            e.CanExecute = true;
        }

        private void WoZExportTypeComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (WoZExportDirectoryTextBox == null)      //Selection gets called before directorybox is initialized
                return;
            if (_cassiniInstalled)
            {
                if (WoZExportTypeComboBox.SelectedIndex == 0)
                {
                    WozExportDirectoryLabel.Content = "Port:";
                }
                //WoZExportDirectoryTextBox.IsEnabled = false;
                else
                    WozExportDirectoryLabel.Content = "Export Directory:";
                //WoZExportDirectoryTextBox.IsEnabled = true;
            }
        }

        private void ExportCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            DialogResult = true;
        }

        private void ExportCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (ActiveStoryApplication.CurrentProject.PageLookupTable.Count == 0)
            {
                MessageBox.Show(this, "There are no pages in the current project.\n\rIf you are working on a page, save it before exporting.", "Error, No Pages", MessageBoxButton.OK, MessageBoxImage.Error);
                //DialogResult = false;         //Causes wierd crashes...
            }
            else
            {
                foreach (int pageNumber in ActiveStoryApplication.CurrentProject.PageLookupTable.Keys)
                {
                    StartupPageNumberComboBox.Items.Add(pageNumber + 1);      //show page numbers base 1
                }
                if (StartupPageNumberComboBox.Items.Count != 0)
                    StartupPageNumberComboBox.SelectedIndex = 0;
                if(ActiveStoryApplication.CurrentProject.PageLookupTable.ContainsKey(ActiveStoryApplication.CurrentPage.PageNumber))
                    PageExportPreviewImage.Source = new BitmapImage(new Uri(ActiveStoryApplication.CurrentProject.PageLookupTable[ActiveStoryApplication.CurrentPage.PageNumber].TempThumbnailPath));
            }
            
            //if this returns null then Cassini isn't installed, so dont show the option
            
            if(!_cassiniInstalled)
            {
                WoZExportTypeComboBox.Items.RemoveAt(0);
                WoZExportTypeComboBox.SelectedIndex = 0;
            }
            else
            {
                WozExportDirectoryLabel.Content = "Port:";
            }
        }
        private bool IsCassiniInstalled()
        {
#if !DEBUG
            try
            {
#endif
            Microsoft.Win32.RegistryKey regKey= Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Components\0A1363317CF17D36C6D899822C4C3A2B");
            if(regKey==null)
                return false;
            if (regKey.GetValue("DEAD8C6F7CC8DF34D94AF126B978A371") == null)
                return false;
            return true;
#if !DEBUG
            }
            catch (NullReferenceException nre)
            {
                return false;
            }
#endif
        }
    }
}
